package controllers

import (
	"cubeAdmin/common"
	"cubeAdmin/common/dada"
	"cubeAdmin/dto"
	"errors"
	"github.com/beego/beego/v2/server/web"
	"log"
	"strings"
)

type BaseController struct {
	web.Controller
}

// Prepare 前期准备
func (c *BaseController) Prepare() {
	version, _ := web.AppConfig.String("version")
	c.Data["version"] = version
	siteName, _ := web.AppConfig.String("site.name")
	c.Data["siteName"] = siteName
}

// GetParams 获取参数
func (c *BaseController) GetParams() dto.BasePage {
	var (
		page   int
		limit  int
		blurry string
	)
	c.Ctx.Input.Bind(&page, "page")
	c.Ctx.Input.Bind(&limit, "limit")
	c.Ctx.Input.Bind(&blurry, "blurry")
	return dto.BasePage{Page: page, Limit: limit, Blurry: blurry}
}

// 获取用户IP地址
func (c *BaseController) getClientIp() string {
	s := c.Ctx.Request.RemoteAddr
	l := strings.LastIndex(s, ":")
	return s[0:l]
}

// PageTable 构建分页数据
func (c *BaseController) PageTable(count int64, data interface{}) {
	var r dada.ResultTable
	r.Code = 0
	r.Count = count
	r.Data = data
	c.Data["json"] = r
	err := c.ServeJSON()
	if err != nil {
		log.Print(errors.New("数据异常"))
	}
}

// DataTree 构建树
func (c *BaseController) DataTree(data interface{}) {
	tree := &dada.ResultTree{
		Status: struct {
			Code    int    `json:"code"`
			Message string `json:"message"`
		}(struct {
			Code    int
			Message string
		}{Code: common.MsgOk, Message: "操作成功"}),
		Data: data,
	}
	c.Data["json"] = tree
	c.ServeJSON()
}

func (c *BaseController) Ok(data any) {
	c.Data["json"] = SuccessData(data)
	c.ServeJSON()
}

func (c *BaseController) OkMsg(data any, msg string) {
	var r dada.Result
	r.Status = common.MsgOk
	r.Msg = msg
	r.Data = data
	c.Data["json"] = r
	c.ServeJSON()
}

func (c *BaseController) Fail(msg string, status int) {
	c.Data["json"] = ErrMsg(msg, status)
	c.ServeJSON()
}

func ErrMsg(msg string, status ...int) dada.Result {
	var r dada.Result
	if len(status) > 0 {
		r.Status = status[0]
	} else {
		r.Status = common.MsgErr
	}
	r.Msg = msg
	r.Data = nil
	return r
}

func ErrData(msg error, status ...int) dada.Result {
	var r dada.Result
	if len(status) > 0 {
		r.Status = status[0]
	} else {
		r.Status = common.MsgErr
	}
	r.Msg = msg.Error()
	r.Data = nil
	return r
}

func SuccessData(data any) dada.Result {
	var r dada.Result

	r.Status = common.MsgOk
	r.Msg = "ok"
	r.Data = data
	return r
}
